/*
 * Copyright (c) 2014 Luca Agostini, Alessandro Cantini, Alessandro Dignani
 *
 * This file is part of MeteoCal.
 *
 * MeteoCal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package it.polimi.se2.agostini_cantini_dignani.meteocal.entity;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.*;
import java.io.Serializable;
import java.util.List;
import java.util.TimeZone;

/**
 * @author Alessandro Cantini <alessandro.cantini@mail.polimi.it>
 */
@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Calendar implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Integer calendarId;

	@XmlAttribute(name = "public")
	@NotNull
	private boolean isPublic;

	@XmlElement(name = "event")
	@JoinTable(name = "PARTICIPATION")
	@ManyToMany
	private List<Event> events;

	@NotNull
	@OneToOne(mappedBy = "calendar")
	private User owner;

	@NotNull
	private String timeZone = TimeZone.getDefault().getID();

	public Calendar() {
	}

	public Integer getCalendarId() {
		return calendarId;
	}

	public void setCalendarId(Integer calendarId) {
		this.calendarId = calendarId;
	}

	public boolean isPublic() {
		return isPublic;
	}

	public void setPublic(boolean isPublic) {
		this.isPublic = isPublic;
	}

	public List<Event> getEvents() {
		return events;
	}

	public void setEvents(List<Event> events) {
		this.events = events;
	}

	public String getTimeZone() {
		return timeZone;
	}

	public void setTimeZone(String timeZone) {
		this.timeZone = timeZone;
	}

	public User getOwner() {
		return owner;
	}

	public void setOwner(User owner) {
		this.owner = owner;

		if (!equals(owner.getCalendar())) {
			owner.setCalendar(this);
		}
	}

	@Override
	public int hashCode() {
		int hash = 0;
		hash += (calendarId != null ? calendarId.hashCode() : 0);
		return hash;
	}

	@Override
	public boolean equals(Object object) {
		if (!(object instanceof Calendar)) {
			return false;
		}
		Calendar other = (Calendar) object;
		if ((this.calendarId == null && other.calendarId != null) || (this.calendarId != null && !this.calendarId.equals(other.calendarId))) {
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		return "Calendar[" +
				"owner=" + owner.getEmail() +
				", calendarId=" + calendarId +
				']';
	}
}
